<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试" prop="examId">
        <el-select
          v-model="queryParams.examId"
          placeholder="请选择关联的考试"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="exam in examList"
            :key="exam.id"
            :label="exam.examName"
            :value="exam.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否批阅" prop="isConfirmed"  >
        <el-select
          v-model="queryParams.isConfirmed"
          placeholder="是否批阅"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="studentexamList" @selection-change="handleSelectionChange">
      <el-table-column label="学生姓名" align="center" prop="userName" />
      <el-table-column label="考试名称" align="center" prop="examName" />
      <el-table-column label="学生开始考试的时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学生结束考试的时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学生考试成绩" align="center" prop="score" />
      <el-table-column label="是否已批阅" align="center" prop="isConfirmed">
        <template #default="scope">
          <span>{{ scope.row.isConfirmed === 1 ? '已批阅' : '未批阅' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right" width="180">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleScore(scope.row)" v-hasPermi="['business:studentexam:edit']">批阅</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看答题记录对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="examFormRef" :model="form" label-width="100px">
        <el-form-item label="考试名称">
          <span>{{ form.examName }}</span>
        </el-form-item>
        <el-form-item label="开始时间">
          <span>{{ parseTime(form.startTime) }}</span>
        </el-form-item>
        <el-form-item label="结束时间">
          <span>{{ parseTime(form.endTime) }}</span>
        </el-form-item>
        
        <el-divider content-position="left">答题记录</el-divider>
        
        <div v-for="(question, index) in form.questionVos" :key="question.questionId" class="question-item">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>第{{ index + 1 }}题 ({{ question.questionType === 'single-choice' ? '单选题' : 
                  question.questionType === 'multiple-choice' ? '多选题' : 
                  question.questionType === 'blank-filling' ? '填空题' : '编程题' }})</span>
                <span>难度: {{ question.difficultyLeve }}</span>
                <span>得分: 
                  <el-input-number 
                    v-if="question.questionType !== 'single-choice' && question.questionType !== 'multiple-choice'"
                    v-model="question.score" 
                    :min="0" 
                    :max="100"
                    size="small"
                    style="width: 100px"
                  />
                  <span v-else>{{ question.score || 0 }}</span>
                </span>
              </div>
            </template>
            <div class="question-content">
              <p><strong>题目内容：</strong>{{ question.questionContent }}</p>
              
              <!-- 选择题选项 -->
              <div v-if="question.options && question.options.length > 0">
                <p><strong>选项：</strong></p>
                <div v-for="option in question.options" :key="option.id" class="option-item">
                  {{ option.optionLetter }}. {{ option.optionContent }}
                </div>
              </div>
              
              <p><strong>学生答案：</strong></p>
              <el-input
                v-if="question.questionType === 'coding'"
                type="textarea"
                v-model="question.answer"
                :rows="4"
                readonly
                class="code-answer"
              />
              <span v-else>{{ question.answer }}</span>

              <p><strong>正确答案：</strong></p>
              <el-input
                v-if="question.questionType === 'coding'"
                type="textarea"
                v-model="question.rightAnswer"
                :rows="4"
                readonly
                class="code-answer"
              />
              <span v-else>{{ question.rightAnswer }}</span>

              <p><strong>是否正确：</strong>
                <el-tag :type="question.isCorrect === 1 ? 'success' : 'danger'">
                  {{ question.isCorrect === 1 ? '正确' : '错误' }}
                </el-tag>
              </p>
            </div>
          </el-card>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitScore">保存分数</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Studentexam">
import { listUserexam, getUserInfoExam, delUserexam, submitScoreApi, updateUserexam } from "@/api/business/studentexam";
import { listNoPage } from  '@/api/business/exam'
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';

const { proxy } = getCurrentInstance();
const { sys_yes_no } =
  proxy.useDict(
    "sys_yes_no"
  );
const studentexamList = ref([]);
const examList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    examId: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    examId: null,
    startTime: null,
    endTime: null,
    score: null,
    isSubmitted: null,
  },
  rules: {
    userId: [
      { required: true, message: "学生id不能为空", trigger: "blur" }
    ],
    examId: [
      { required: true, message: "关联的考试id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生考试表列表 */
function getList() {
  loading.value = true;
  listUserexam(queryParams.value).then(response => {
    studentexamList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getExamList(){
  listNoPage(null).then(response => {
    examList.value = response.data;
    if (examList.value.length > 0) {
      form.value.examId = examList.value[0].id;
      queryParams.value.examId = examList.value[0].id;
    }
    console.log(examList.value)
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    examId: null,
    startTime: null,
    endTime: null,
    score: null,
    isSubmitted: null,
    createTime: null,
    updateTime: null
  };
  if (examList.value.length > 0) {
    form.value.examId = examList.value[0].id;
  }
  proxy.resetForm("studentexamRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  if (examList.value.length > 0) {
    queryParams.value.examId = examList.value[0].id;
  }
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生考试表";
}

/** 修改按钮操作 */
function handleScore(row) {
  reset();
  const userId = row.userId
  const examId = row.examId
  getUserInfoExam(userId, examId).then(response => {
    form.value = response.data;
    form.value.userId = userId
    open.value = true;
    title.value = "查看答题记录";
  });
}

/** 提交分数 */
function submitScore() {
  const submitData = {
    examId: form.value.examId,
    userId: form.value.userId,
    userAnswerList: form.value.questionVos.map(question => ({
      questionId: question.questionId,
      score: question.score || 0
    }))
  };
  submitScoreApi(submitData).then(response => {
    proxy.$modal.msgSuccess("保存成功");
    open.value = false;
    getList();
  })
 
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学生考试表编号为"' + _ids + '"的数据项？').then(function() {
    return delUserexam(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/userexam/export', {
    ...queryParams.value
  }, `userexam_${new Date().getTime()}.xlsx`)
}

getList();
getExamList();
</script>

<style scoped>
.question-item {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.question-content {
  padding: 10px;
}
.option-item {
  margin: 5px 0;
  padding-left: 20px;
}
.code-answer {
  margin: 10px 0;
  font-family: monospace;
}
</style>
    